﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Billing.Utilities;
using Billing.Dtos;
using System.Windows.Controls.Primitives;
using Billing.Controls;

namespace Billing.Windows
{
    public partial class DamageStock : Window
    {
        public string code = string.Empty;
        public string desc = string.Empty;

        public DamageStock()
        {
            try
            {
                InitializeComponent();

                BindAllItemstoGrid(CacheManager.BillingItems);
                txtCodeSearch.Focus();

                lbAddStock.Text = "Add Damage";
            }
            catch (Exception) { }
        }

        private void BindAllItemstoGrid(List<BillingGridItemDto> list)
        {
            try
            {
                List<StockItemControl> mainList = new List<StockItemControl>();
                mainList.Add(new StockItemControl());
                foreach (BillingGridItemDto item in list)
                {
                    StockItemControl stockItem = new StockItemControl();
                    stockItem.lblCode.Content = item.Code;
                    stockItem.lblDescription.Content = item.Name;
                    stockItem.lblStock.Content = item.Stock;
                    stockItem.lblPrice.Content = item.Price;
                    stockItem.lblAcceptDecimalStock.Content = item.AcceptDecimalStock;
                    mainList.Add(stockItem);
                }

                lbStockGrid.ItemsSource = mainList;
            }
            catch (Exception) { }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Escape)
                {
                    this.Close();
                }
            }
            catch (Exception) { }
        }

        private bool ValidateFields(BillingGridItemDto item)
        {
            try
            {
                double result;
                if (txtItemQty.Text.Trim() == string.Empty)
                {
                    txtItemQty.Focus();
                    return false;
                }
                else
                {
                    string qty = txtItemQty.Text;
                    if (item.AcceptDecimalStock)
                    {
                        if (!(double.TryParse(qty, out result)))
                        {
                            MessageBox.Show("Please enter valid Item Qty", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            txtItemQty.Text = string.Empty;
                            return false;
                        }
                    }
                    else
                    {
                        int res;
                        if (!(int.TryParse(qty, out res)))
                        {
                            MessageBox.Show("Please enter valid Item Qty", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            txtItemQty.Text = string.Empty;
                            return false;
                        }
                        result = res;
                    }
                }

                //if (Convert.ToDouble(((StockItemControl)lbStockGrid.SelectedItem).lblStock.Content) < result)
                //{
                //    MessageBox.Show("Enter Qty exceeds Available Stock", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                //    txtItemQty.Text = string.Empty;
                //    return false;
                //}

                return true;
            }
            catch (Exception) 
            {
                return false;
            }
        }

        void AddDamage()
        {
            try
            {
                BillingGridItemDto selectedItem = (BillingGridItemDto)GetSelectedStockItem((StockItemControl)lbStockGrid.SelectedItem);
                int selectedItemCode = selectedItem.Code;

                if (ValidateFields(selectedItem))
                {
                    int result = Database.AddDamage(selectedItemCode, double.Parse(txtItemQty.Text.Trim()));
                    if (result != 0)
                    {
                        txtItemQty.Clear();
                        txtCodeSearch.Clear();
                        txtCodeSearch.Focus();
                        MessageBox.Show("Stock Damage Added", "Damage Added", MessageBoxButton.OK);
                        CacheManager.ResetCacheManager();
                        lbStockGrid.ItemsSource = null;
                        BindAllItemstoGrid(CacheManager.BillingItems);
                        //this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Some Error Has Occurred", "Damage Not Added", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            catch (Exception) { }
        }

        BillingGridItemDto GetSelectedStockItem(StockItemControl selectedItem)
        {
            try
            {
                BillingGridItemDto item = new BillingGridItemDto();
                item.Code = Convert.ToInt32(selectedItem.lblCode.Content.ToString().Trim());
                item.Qty = Convert.ToDouble(selectedItem.lblStock.Content.ToString().Trim());
                item.Name = selectedItem.lblDescription.Content.ToString().Trim();
                item.Price = Convert.ToDouble(selectedItem.lblPrice.Content.ToString().Trim());
                item.AcceptDecimalStock = Convert.ToBoolean(selectedItem.lblAcceptDecimalStock.Content.ToString().Trim());
                return item;
            }
            catch (Exception) 
            {
                return null;
            }
        }

        private void dGAllItems_EnterKey(object sender, RoutedEventArgs e)
        {
            try
            {
                txtItemQty.Focus();
            }
            catch (Exception) { }
        }

        List<BillingGridItemDto> SearchResult()
        {
            try
            {
                List<Dtos.BillingGridItemDto> items = Utilities.CacheManager.BillingItems;
                List<Dtos.BillingGridItemDto> results = new List<Dtos.BillingGridItemDto>();
                string pattern = txtCodeSearch.Text.Trim();
                foreach (BillingGridItemDto item in items)
                    if (System.Text.RegularExpressions.Regex.IsMatch(item.Name.Trim(), pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase) || System.Text.RegularExpressions.Regex.IsMatch(item.Code.ToString().Trim(), pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                        results.Add(item);

                return results;
            }
            catch (Exception) 
            {
                return null;
            }
        }

        private void txtCodeSearch_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    BindAllItemstoGrid(SearchResult());
                }
                else if (e.Key == Key.Down && lbStockGrid.Items.Count > 0)
                {
                    TraversalRequest request = new TraversalRequest(FocusNavigationDirection.Next);
                    UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
                    if (elementWithFocus != null)
                        elementWithFocus.MoveFocus(request);
                }
            }
            catch (Exception) { }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Key == Key.Enter)
                {
                    if (txtItemQty.IsFocused)
                    {
                        AddDamage();
                    }
                    else if (txtCodeSearch.IsFocused)
                    {
                        BindAllItemstoGrid(SearchResult());
                        if (lbStockGrid.Items.Count > 1)
                        {
                            lbStockGrid.Focus();
                            lbStockGrid.SelectedIndex = 0;
                        }
                    }
                    else if (lbStockGrid.SelectedItems.Count == 1)
                    {
                        txtItemQty.Focus();

                        (lbStockGrid.SelectedItem as StockItemControl).lblCode.Foreground = new SolidColorBrush(Colors.Red);
                        (lbStockGrid.SelectedItem as StockItemControl).lblCode.FontWeight = FontWeights.Bold;

                        (lbStockGrid.SelectedItem as StockItemControl).lblDescription.Foreground = new SolidColorBrush(Colors.Red);
                        (lbStockGrid.SelectedItem as StockItemControl).lblDescription.FontWeight = FontWeights.Bold;

                        (lbStockGrid.SelectedItem as StockItemControl).lblPrice.Foreground = new SolidColorBrush(Colors.Red);
                        (lbStockGrid.SelectedItem as StockItemControl).lblPrice.FontWeight = FontWeights.Bold;

                        (lbStockGrid.SelectedItem as StockItemControl).lblStock.Foreground = new SolidColorBrush(Colors.Red);
                        (lbStockGrid.SelectedItem as StockItemControl).lblStock.FontWeight = FontWeights.Bold;
                    }
                }
            }
            catch (Exception) { }
        }

        private void lbStockGrid_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Left)
            {
                lbStockGrid.SelectedIndex = -1;
                txtCodeSearch.Focus();
                txtCodeSearch.SelectAll();
            }
        }

        private void txtItemQty_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Left)
            {
                if (lbStockGrid.SelectedItem != null)
                {
                    (lbStockGrid.SelectedItem as StockItemControl).lblCode.Foreground = new SolidColorBrush(Colors.White);
                    (lbStockGrid.SelectedItem as StockItemControl).lblCode.FontWeight = FontWeights.Light;

                    (lbStockGrid.SelectedItem as StockItemControl).lblDescription.Foreground = new SolidColorBrush(Colors.White);
                    (lbStockGrid.SelectedItem as StockItemControl).lblDescription.FontWeight = FontWeights.Light;

                    (lbStockGrid.SelectedItem as StockItemControl).lblPrice.Foreground = new SolidColorBrush(Colors.White);
                    (lbStockGrid.SelectedItem as StockItemControl).lblPrice.FontWeight = FontWeights.Light;

                    (lbStockGrid.SelectedItem as StockItemControl).lblStock.Foreground = new SolidColorBrush(Colors.White);
                    (lbStockGrid.SelectedItem as StockItemControl).lblStock.FontWeight = FontWeights.Light;
                }
                lbStockGrid.Focus();
                //lbStockGrid.SelectedIndex = -1;
            }
        }
    }
}